# -*- coding: utf-8 -*-

import json

from django.conf import settings
from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView
from pymongo import MongoClient

from common.admin import db as user_db
from common.channel import admin_db as channel_db
from common.settlement import db as settlement_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper, safe_wrapper
from common.utils.tz import utc_to_local_str, local_now

_LOGGER = track_logging.getLogger(__name__)

mg = MongoClient(settings.MONGO_ADDR).paychannel_stat


def get_channel_today_income(channel_id):
    id = str(channel_id) + '_' + local_now().strftime('%Y%m%d')
    channel_daily_data = mg.channel_status.find_one({"_id": id})
    if channel_daily_data:
        return channel_daily_data['total']
    else:
        return 0


def get_channels_today_income(channel_id, chn_ids):
    if chn_ids == None:
        chn_ids = ''
    ids = [int(y) for y in chn_ids.split(',')]
    if str(channel_id) not in chn_ids:
        ids.append(channel_id)
    income = 0
    for id in ids:
        income += get_channel_today_income(id)
    return income


class SettlementView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('mch_id', ''):
            query_dct['mch_id'] = cond
        _LOGGER.info('SettlementView get: %s, ', query_dct)

        items, total_count = settlement_db.list_settlement(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    @method_decorator(safe_wrapper)
    def post(self, req):
        param_dct = json.loads(req.body)
        if param_dct.get('mch_id') is None:
            param_dct['mch_id'] = channel_db.get_channel(int(param_dct['chn_id'])).mch_id
        if param_dct.get('name') is None:
            param_dct['name'] = u'[结算]' + channel_db.get_channel(int(param_dct['chn_id'])).name
        if param_dct.get('rate') is None:
            param_dct['rate'] = channel_db.get_channel(int(param_dct['chn_id'])).rate
        if param_dct.get('today_income') is None:
            param_dct['today_income'] = get_channels_today_income(int(param_dct['chn_id']),
                                                                  param_dct.get('chn_ids', ''))
        if param_dct.get('warning_amount') is None:
            param_dct['warning_amount'] = 50000
        if param_dct.get('status') is None:
            param_dct['status'] = 0
        if param_dct.get('balance') is None:
            param_dct['balance'] = 0
        param_dct['today_withdraw'] = 0
        settlement_db.upsert_settlement(param_dct)
        return {}

    def put(self, req):
        return self.post(req)

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SettlementView, self).dispatch(*args, **kwargs)


class SingleSettlementView(TemplateView):
    def get(self, req, id):
        mch_user = settlement_db.get_settlement(id=int(id))
        data = mch_user.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, id):
        return self.put(req, id)

    def put(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        settlement_db.upsert_settlement(query_dct, int(id))
        return {}

    def patch(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        s = settlement_db.get_settlement(id=int(id))
        if query_dct.get('balance') and not query_dct.get('today_income'):
            query_dct['today_income'] = get_channel_today_income(s.chn_id, s.chn_ids)
        settlement_db.upsert_settlement(query_dct, int(id))
        return {}

    def delete(self, req, id):
        settlement_db.delete_settlement(int(id))
        _LOGGER.info('delete settlement: %s, user: %s', id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleSettlementView, self).dispatch(*args, **kwargs)
